package com.lxx.utils;

import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;

import com.lxx.common.ErrCode;
import com.lxx.exception.ConstraintException;

public class ValidationUtils {
	
	private static final Validator VALIDATOR = Validation.buildDefaultValidatorFactory().getValidator();
	
	public static <T> ValidationResult validate(T t) {
		ValidationResult validationResult = new ValidationResult();
		Set<ConstraintViolation<T>> constraintViolations = VALIDATOR.validate(t);
		for (ConstraintViolation<T> constraintViolation : constraintViolations) {
			validationResult.addErrMsg(constraintViolation.getPropertyPath()+", "+constraintViolation.getMessage());
		}
		
		return validationResult;
	}
	
	/**
	 * 验证, 不通过时会抛异常
	 * @param t
	 * @return
	 */
	public static <T> ValidationResult validateForce(T t) {
		ValidationResult validationResult = new ValidationResult();
		Set<ConstraintViolation<T>> constraintViolations = VALIDATOR.validate(t);
		for (ConstraintViolation<T> constraintViolation : constraintViolations) {
			validationResult.addErrMsg(constraintViolation.getPropertyPath()+", "+constraintViolation.getMessage());
		}
		
		if (validationResult.isHasError()) {
			throw new ConstraintException(ErrCode.CONSTRAINT_FAIL, 
					String.join("|", validationResult.getErrMsgs()));
		}
		
		return validationResult;
	}

}
